// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package tidb

import (
	"encoding/hex"

	"github.com/gtank/cryptopasta"
	"github.com/joomcode/errorx"

	"github.com/pingcap-incubator/tidb-dashboard/pkg/model"
)

var (
	ErrNS                 = errorx.NewNamespace("error.tidb")
	ErrInstance           = ErrNS.NewSubNamespace("instance")
	ErrInstanceEncryptErr = ErrInstance.NewType("encrypt_err")
	ErrInstanceDecryptErr = ErrInstance.NewType("decrypt_err")
)

func EncryptInstanceParam(instance *model.TidbInstance, key string) error {
	encryptedPassword, err := Encrypt(instance.Password, key)
	if err != nil {
		return err
	}
	instance.Password = encryptedPassword
	return nil
}

func DecryptInstanceParam(instance *model.TidbInstance, key string) error {
	decryptedPassword, err := Decrypt(instance.Password, key)
	if err != nil {
		return err
	}
	instance.Password = decryptedPassword
	return nil
}

func Encrypt(plain string, key string) (string, error) {
	secret := &[32]byte{}
	copy(secret[:], key)
	encrypted, err := cryptopasta.Encrypt([]byte(plain), secret)
	if err != nil {
		return "", ErrInstanceEncryptErr.Wrap(err, "encrypt err")
	}
	return hex.EncodeToString(encrypted), nil
}

func Decrypt(ciphertext string, key string) (string, error) {
	secret := &[32]byte{}
	copy(secret[:], key)
	encrypted, err := hex.DecodeString(ciphertext)
	if err != nil {
		return "", ErrInstanceDecryptErr.Wrap(err, "decrypt err")
	}
	decrypted, err := cryptopasta.Decrypt(encrypted, secret)
	if err != nil {
		return "", ErrInstanceDecryptErr.Wrap(err, "decrypt err")
	}
	return string(decrypted), nil
}
